﻿using Padsurface.Audio.Engine.Interfaces;
using Padsurface.Audio.Wave;
using System;
using System.Collections.Concurrent;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;

namespace Padsurface.Audio.Engine
{
    [Export(typeof(IPlayBuffer))]
    internal class PlayBuffer : IPlayBuffer
    {
        private CancellationTokenSource _cancellationTokenSource;

        public BlockingCollection<WaveFileOutput> Buffer { get; private set; }

        public PlayBuffer()
        {
            _cancellationTokenSource = new CancellationTokenSource();
            Buffer = new BlockingCollection<WaveFileOutput>(new ConcurrentQueue<WaveFileOutput>());
        }

        public void Start()
        {
            _cancellationTokenSource.Cancel();
            _cancellationTokenSource = new CancellationTokenSource();

            Task.Factory.StartNew(o =>
            {
                while (!_cancellationTokenSource.IsCancellationRequested)
                {
                    Buffer.Take(_cancellationTokenSource.Token).StartPlaying();
                }
            }, _cancellationTokenSource);
        }

        public void Stop()
        {
            _cancellationTokenSource.Cancel();
        }
    }
}